#include "stdafx.h"
#include "net/HTTPServerSession.hpp"
#include "net/Socket.hpp"

NET_NAMESPACE_BEGIN

CHTTPServerSession::CHTTPServerSession(const CStreamSocket& socket, CHTTPServerParams::Ptr pParams)
	: CHTTPSession(socket, pParams->getKeepAlive()),
	m_firstRequest(true),
	m_keepAliveTimeout(pParams->getKeepAliveTimeout()),
	m_maxKeepAliveRequests(pParams->getMaxKeepAliveRequests())
{
	setTimeout(pParams->getTimeout());
	this->socket().setReceiveTimeout(pParams->getTimeout());
}

CHTTPServerSession::~CHTTPServerSession()
{
}

bool CHTTPServerSession::hasMoreRequests()
{
	if (!socket().impl()->initialized()) return false;

	if (m_firstRequest)
	{
		m_firstRequest = false;
		--m_maxKeepAliveRequests;
		return socket().poll(getTimeout(), CSocket::SELECT_READ);
	}
	else if (m_maxKeepAliveRequests != 0 && getKeepAlive())
	{
		if (m_maxKeepAliveRequests > 0) 
			--m_maxKeepAliveRequests;
		return buffered() > 0 || socket().poll(m_keepAliveTimeout, CSocket::SELECT_READ);
	}
	else return false;
}

bool CHTTPServerSession::canKeepAlive() const
{
	return m_maxKeepAliveRequests != 0;
}

CSocketAddress CHTTPServerSession::clientAddress()
{
	return socket().peerAddress();
}

CSocketAddress CHTTPServerSession::serverAddress()
{
	return socket().address();
}

NET_NAMESPACE_END
